package ext.acae2.change.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import wt.doc.WTDocument;
import wt.enterprise.RevisionControlled;
import wt.fc.Persistable;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.util.WTException;
import wt.util.WTMessage;
import wt.util.WTRuntimeException;

import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.core.ui.validation.DefaultUIComponentValidator;
import com.ptc.core.ui.validation.UIValidationCriteria;
import com.ptc.core.ui.validation.UIValidationFeedbackMsg;
import com.ptc.core.ui.validation.UIValidationKey;
import com.ptc.core.ui.validation.UIValidationResult;
import com.ptc.core.ui.validation.UIValidationStatus;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.utilResource;
import com.ptc.netmarkets.util.misc.NmContext;

import ext.acae2.ACAEConstants;
import ext.acae2.change.helper.ChangeTaskHelper;
import ext.acae2.change.resource.ECNResource;
import ext.acae2.part.PartHelper;

/**
 * @desription revise item
 * @author cnie
 * @date 2013-5-15 上午1:06:00
 */
public class ReviseAffectedDataValidator extends DefaultUIComponentValidator {

	private static final Logger LOGGER = LogR
			.getLogger(ReviseAffectedDataValidator.class.getName());

	private static final String RESOURCE = ECNResource.class.getName();

	private static final String UTILRESOURCE = utilResource.class.getName();

	@Override
	public UIValidationResult validateFormSubmission(
			UIValidationKey uivalidationkey,
			UIValidationCriteria uivalidationcriteria, Locale locale)
			throws WTException {
		LOGGER.debug("-->ReviseAffectedDataValidator start");
		UIValidationResult uivalidationresult = UIValidationResult.newInstance(
				uivalidationkey, UIValidationStatus.PERMITTED);
		java.util.Map map = uivalidationcriteria.getParameterMap();
		String changeMode = ((String[]) map.get("changeMode"))[0];
//		String affectedTableId = ((String[]) map.get("affectedTableId"))[0];
		String ecnType = uivalidationcriteria.getTextParameter("ecnType");
		if (StringUtils.isNotBlank(ecnType)) {
			if (ecnType.indexOf(ACAEConstants.ACAE2_TYPE_FILE_ECN) < 0
					&& ecnType
							.indexOf(ACAEConstants.ACAE2_TYPE_PARTDRAWING_ECN) < 0) {
				return uivalidationresult;
			}
		}
		
		List<NmOid> initItemList = new ArrayList<NmOid>();
		NmOid primaryNmoid = null;
		if("create".equalsIgnoreCase(changeMode)){
			initItemList = uivalidationcriteria
					.getInitialItemsByName("changeTask_affectedItems_table");
			primaryNmoid = initItemList.get(0);
		}else if("edit".equalsIgnoreCase(changeMode)){
			initItemList = uivalidationcriteria.getInitialItemsByName("changeTask_resultingItems_table");
			List<RevisionControlled> releatedItems = new ArrayList<RevisionControlled>(); // 主对象part的关联的所有对象信息
			for (NmOid initNmoid : initItemList) {
				if (initNmoid.isA(WTPart.class)) {
					WTPart initPart = (WTPart) initNmoid.getWtRef()
							.getObject();
					if (!releatedItems.contains(initPart)) {
						primaryNmoid = initNmoid;
						ChangeTaskHelper.getPrimaryRelectedCADDocs(
								initPart, releatedItems);
					}
				}
			}
			
		}

		String errorStr = null;
		List<NmContext> nmContextList = uivalidationcriteria.getSelected();
		if (nmContextList == null || nmContextList.size() == 0) {
			errorStr = WTMessage.getLocalizedMessage(UTILRESOURCE,
					utilResource.NONE_CHECKED, null, locale);
		} else {
			
			if (primaryNmoid.isA(WTDocument.class)) {
				WTDocument primaryDoc = (WTDocument) primaryNmoid.getWtRef()
						.getObject();
				boolean isFileECNRevise = checkFileECNRevise(primaryDoc,
						nmContextList);
				if (!isFileECNRevise) {
					errorStr = WTMessage.getLocalizedMessage(RESOURCE,
							ECNResource.REVISE_PRIMARY_OBJ_ERROR,
							new String[] { primaryDoc.getNumber() }, locale);
				}
			} else {
				WTPart rootPart = null; // 此次受影响对象主对象部件
				List<RevisionControlled> releatedItems = new ArrayList<RevisionControlled>(); // 主对象part的关联的所有对象信息
				for (NmOid initNmoid : initItemList) {
					if (initNmoid.isA(WTPart.class)) {
						WTPart initPart = (WTPart) initNmoid.getWtRef()
								.getObject();
						if (!releatedItems.contains(initPart)) {
							rootPart = initPart;
							ChangeTaskHelper.getPrimaryRelectedCADDocs(
									initPart, releatedItems);
						}
					}
				}
				boolean isFileECNRevise = checkPartRevise(rootPart,
						nmContextList);
				if (!isFileECNRevise) {
					errorStr = WTMessage.getLocalizedMessage(RESOURCE,
							ECNResource.REVISE_PRIMARY_RELEATED_OBJ_ERROR,
							new String[] { rootPart.getNumber() }, locale);
				}

			}
		}

		if (StringUtils.isNotBlank(errorStr)) {
			uivalidationresult.setStatus(UIValidationStatus.DENIED);
			uivalidationresult.addFeedbackMsg(UIValidationFeedbackMsg
					.newInstance(errorStr, FeedbackType.ERROR));
		}
		LOGGER.debug("-->ReviseAffectedDataValidator end");
		return uivalidationresult;
	}

	private static boolean checkFileECNRevise(WTDocument primaryDoc,
			List<NmContext> nmContextList) {
		boolean isFileECNRevise = true;
		for (NmContext nmContext : nmContextList) {

			try {
				Persistable p = nmContext.getTargetOid().getWtRef().getObject();
				RevisionControlled selRc = (RevisionControlled)p;
				LOGGER.debug("selectObjs========>"
						+ p.getPersistInfo().getObjectIdentifier()
								.getStringValue());

				LOGGER.debug("primaryDoc========>"
						+ primaryDoc.getPersistInfo().getObjectIdentifier()
								.getStringValue());

				if (!primaryDoc.getMaster().equals(selRc.getMaster())) {
					isFileECNRevise = false;
					break;
				}
			} catch (WTRuntimeException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (WTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return isFileECNRevise;
	}

	/**
	 * 
	 * @description check primary part releated Revise
	 * @author cnie
	 * @date 2013-5-15 上午11:35:58
	 * @version 1.0
	 * @param primaryPart
	 * @param selectObjs
	 * @return
	 */
	private static boolean checkPartRevise(WTPart primaryPart,
			List<NmContext> selectObjs) {
		boolean isPartReleatedRevise = false;
		try {
			List<RevisionControlled> rcs = new ArrayList<RevisionControlled>();
			rcs = ChangeTaskHelper.getPrimaryRelectedCADDocs(primaryPart, rcs);
			rcs.add(primaryPart);
			for (NmContext nmContext : selectObjs) {
				isPartReleatedRevise = false;
				Persistable p = nmContext.getTargetOid().getWtRef().getObject();
				RevisionControlled selRc = (RevisionControlled)p;
				for (RevisionControlled rc : rcs) {
					if (rc.getMaster().equals(selRc.getMaster())) {
						isPartReleatedRevise = isPartReleatedRevise || true;
						break;
					}
				}
				if (!isPartReleatedRevise) {
					break;
				}
			}
		} catch (WTException e) {
			e.printStackTrace();
		}
		return isPartReleatedRevise;
	}

}
